package com.bsy.common.base

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.bsy.framework.base.BaseDataBindFragment
import com.bsy.framework.base.PermissionRequestCode
import com.bsy.framework.toast.Toaster
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.lang.reflect.ParameterizedType

/**
 * @author Sincerity
 * @date   2023/2/27 12:31
 * @desc   DataBinding和ViewModel基类
 */
abstract class BasePermissionFragment<DB : ViewDataBinding, VM : ViewModel> : BaseDataBindFragment<DB>() {
    lateinit var mViewModel: VM
    private var requestCode: Int = 0

    //相机
    private val camera = Permission.CAMERA

    //拍照回调
    var mActivityResultLauncherTake: ActivityResultLauncher<Intent>? = null

    //相机拍照URI
    var photoUri: Uri? = null


    //拨打电话
    private val callPhone = Permission.CALL_PHONE

    /**
     * 读权限
     */
    //11以下
    private val SDK9 = mutableListOf(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
    private val SDK12 = mutableListOf(Permission.MANAGE_EXTERNAL_STORAGE)
    val SDK13 = mutableListOf(Permission.READ_MEDIA_IMAGES, Permission.READ_MEDIA_VIDEO)

    //音频
    val SDK13Audio = mutableListOf(Permission.READ_MEDIA_AUDIO)


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initViewModel()
        super.onViewCreated(view, savedInstanceState)
    }

    open fun initViewModel() {
        val argument = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
        mViewModel = ViewModelProvider(this)[argument[1] as Class<VM>]
    }

    /**
     * 是否拥有相机权限
     */
    private fun hasCameraPermission(): Boolean? = context?.let { XXPermissions.isGranted(it, camera) }

    /**
     * 是否拥有相册视频
     */
    private fun hasReadPermission(): Boolean? =
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
            context?.let { XXPermissions.isGranted(it, SDK12[0]) }
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
            context?.let { XXPermissions.isGranted(it, SDK13[0]) }
        else
            context?.let { XXPermissions.isGranted(it, SDK9[0]) }

    /**
     * 检查摄像头权限
     *
     */
    fun startCheckCameraPermission(code: PermissionRequestCode) {
        if (hasCameraPermission() == true && hasReadPermission() == true)
            onPermissionPassed(code.value)
        else
            XXPermissions.with(context ?: requireContext()).interceptor(com.bsy.common.permission.PermissionInterceptor())
                .permission(
                    camera, if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) SDK9[0]
                    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) SDK13[0]
                    else SDK12[0]
                ).request { _, allGranted ->
                    if (allGranted)
                        onPermissionPassed(code.value)
                    else
                        Toaster.show("缺少必要的系统权限")

                }
    }

    /**
     * 检查申请相册视频权限
     *
     */
    fun startCheckSDCardPermission(code: PermissionRequestCode) {

        if (hasReadPermission() == true)
            onPermissionPassed(code.value)
        else
            startRequestReadAndWriteSd(code.value)
    }

    /**
     * 申请相册视频权限
     *
     */

    private fun startRequestReadAndWriteSd(value: Int) {
        XXPermissions.with(context ?: requireContext())
            .interceptor(com.bsy.common.permission.PermissionInterceptor())
            .permission(
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) SDK9
                else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) SDK13
                else SDK12
            ).request { _, allGranted ->
                if (allGranted)
                    onPermissionPassed(value)
                else
                    Toaster.show("缺少必要的系统权限")

            }
    }


    /**
     * 调取本地相机拍照
     */
    fun takePictures() {
        val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val values = ContentValues()
        //根据uri查询图片地址
        photoUri = requireActivity().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        //放入拍照后的地址
        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
        //调起拍照
        mActivityResultLauncherTake?.launch(takeIntent)
    }


    /**
     * 打电话权限
     */
    fun startRequestCallPhone(phoneNumber: String, code: PermissionRequestCode) {
        XXPermissions.with(context ?: requireContext()).interceptor(com.bsy.common.permission.PermissionInterceptor()).permission(callPhone)
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_DIAL).apply {
                        data = Uri.parse("tel:$phoneNumber")
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                    requireContext().startActivity(intent)
                } else {
                    Toaster.show("缺少必要的系统权限")
                }
            }
    }

    /**
     * 拥有权限的回调
     *
     */
    abstract fun onPermissionPassed(code: Int)

}